package com.shijie.aop;

import com.shijie.aop.annotation.AutoTimeFill;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;

import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.util.Arrays;

@Slf4j
@Aspect
public class AutoTimeFillAspect {
//execution(* *.*.* (..)) &&
    @Pointcut(value = "@annotation(com.shijie.aop.annotation.AutoTimeFill))")
    private void autoTimeFillPointcut() {
    }

    @Before(value = "autoTimeFillPointcut()")
    private void autoFillTime(JoinPoint joinPoint) throws Throwable {
        // 获取方法签名
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();

        // 获取注解及值
        AutoTimeFill annotation = signature.getMethod().getAnnotation(AutoTimeFill.class);
        String[] values = annotation.value();

        // 获取参数列表，规定第一个参数位要填充的实体对象参数
        Object[] args = joinPoint.getArgs();

        if (args == null || args.length == 0) {
            log.warn("填充参数错误，args【{}】", Arrays.toString(args));
            return;
        }
        Object fillEntity = args[0];

        // 开始时间填充
        for (String value : values) {
            try {
                Method setTimeMethod = fillEntity.getClass()
                        .getDeclaredMethod(value, LocalDateTime.class);
                setTimeMethod.setAccessible(true);
                Object invoke = setTimeMethod.invoke(fillEntity, LocalDateTime.now());
                log.info("自动时间填充invoke:【{}】", invoke);
            } catch (Exception e) {
                throw new Exception(e);
            }
        }
        log.info("自动时间填充完成");

    }

}
